public class LongestValidParentheses {
    // leetcode 最长有效括号
    // https://leetcode.cn/problems/longest-valid-parentheses/description/?envType=study-plan-v2&envId=top-100-liked
    public int longestValidParentheses(String s) {
        // left记录有效的左括号的数量， right记录有效的右括号的数量
        int left = 0, right = 0;
        // count记录有效的括号的数量，max记录最大数量
        int count = 0, max = 0;
        for (char c : s.toCharArray()) {
            if (c == '(') left++;
            else {
                if (left <= 0) {
                    left = 0;
                    count = 0;
                }else {
                    count += 2;
                    left--;
                    max = Math.max(max, count);
                }
            }
        }
        return max;
    }

    public static void main(String[] args) {
        LongestValidParentheses lp = new LongestValidParentheses();
        System.out.println(lp.longestValidParentheses(")()())"));
    }
}
